﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Douban.Core;
using System.Windows.Input;
using Microsoft.Practices.Composite.Presentation.Commands;
using Douban.Api;
using Douban.Api.User;
using Douban.Api.Broadcast;
using Douban.Modules.Broadcast.Views;
using System.Collections.ObjectModel;

namespace Douban.Modules.Broadcast.ViewModels
{
    public class BroadcastViewModel : ObservableObject, IBroadcastViewModel
    {
        private DoubanService _doubanService;
        private UserDetail _currentUser;
        private MiniblogFeed _miniblogFeed;
        private ObservableCollection<BroadcastItemViewModel> _broadcastItems;

        public BroadcastViewModel(DoubanService doubanService, IBroadcastView view)
        {
            _doubanService = doubanService;
            View = view;
            View.Context = this;
            Initialize();
        }

        private void Initialize()
        {
            _currentUser = _doubanService.UserService.GetCurrentUser();
        }

        private bool IsMiniblogMatch(Miniblog blog1, Miniblog blog2)
        {
            return blog1.Id == blog2.Id;
        }

        #region IBroadcastViewModel Members

        public IBroadcastView View { get; set; }

        public MiniblogFeed MiniblogFeed 
        {
            get { return _miniblogFeed; }
            set
            {
                _miniblogFeed = value;
                if(BroadcastItems == null)
                    BroadcastItems = new ObservableCollection<BroadcastItemViewModel>();
                
                IList<Miniblog> miniblogs = _miniblogFeed.Miniblogs;

                if (BroadcastItems.Count == 0)
                {
                    foreach (var miniblog in miniblogs)
                        BroadcastItems.Add(new BroadcastItemViewModel(miniblog));
                    return;
                }

                for (int i = 0; i < miniblogs.Count; i++)
                {
                    if (!IsMiniblogMatch(miniblogs[i], BroadcastItems[i].Miniblog))
                    {
                        BroadcastItems.Insert(i, new BroadcastItemViewModel(miniblogs[i]));
                    }
                    else
                    {
                        BroadcastItems[i].Miniblog = miniblogs[i]; 
                    }
                }
            }
        }

        #endregion

        public ObservableCollection<BroadcastItemViewModel> BroadcastItems 
        {
            get { return _broadcastItems; }
            set
            {
                if (_broadcastItems != value)
                {
                    _broadcastItems = value;
                    NotifyPropertyChanged("BroadcastItems");
                }
            }
        }
    }
}
